<?php
if ( !defined( '_PS_VERSION_' ) )
  exit;

class YouTubeChannel extends Module
{
	function __construct()
	{
		$this->name = 'youtubechannel';
		$this->tab = 'front_office_features';
		$this->version = 1.1;
		$this->author = 'kik-off';
        $this->need_instance = 0;

		parent::__construct();

		$this->page = basename(__FILE__, '.php');
		$this->displayName = $this->l('YouTube Channel');
		$this->description = $this->l('YouTube Channel for Prestashop');
	}

	function install()
	{
		Configuration::updateValue('YT_USER', '');
		Configuration::updateValue('YT_DISPLAY_VIDEOS', 10);
		Configuration::updateValue('YT_DESC_TRUNC', 205);
		Configuration::updateValue('YT_HTML5', 1);
		Configuration::updateValue('YT_AUTO_PLAY', 1);
		Configuration::updateValue('YT_PLAYER_WIDTH', '1024');
		Configuration::updateValue('YT_PLAYER_HEIGHT', '576');
		Configuration::updateValue('YT_MODULE_THUMB_WIDTH', '181');
		Configuration::updateValue('YT_MODULE_THUMB_HEIGHT', '136');
		Configuration::updateValue('YT_FEATURED_VIDEOS', 0);
		Configuration::updateValue('YT_MODULE_ORDER', 'published');
		Configuration::updateValue('YT_VIDEO1', '');
		Configuration::updateValue('YT_VIDEO2', '');
		Configuration::updateValue('YT_MODULE_COLOR', 1);
		Configuration::updateValue('YT_ICON_COLOR', 1);

		$this->installRewriteUrl();
		
		if (version_compare(_PS_VERSION_,'1.5','<')){
			$copycontroller = @copy(_PS_MODULE_DIR_.'youtubechannel/movefiles/YoutubeChannelController.php', _PS_CONTROLLER_DIR_.'YoutubeChannelController.php');
		}
		else{
            $copycontroller = @copy(_PS_MODULE_DIR_.'youtubechannel/movefiles/YoutubeChannelController.php', _PS_CONTROLLER_DIR_.'front/YoutubeChannelController.php');
		}  

		if ( parent::install() == false 
		    OR !$this->registerHook( 'header' ) 
			OR !$this->registerHook('leftColumn') 
			OR !@copy(_PS_MODULE_DIR_.'youtubechannel/movefiles/youtubechannel.php', _PS_ROOT_DIR_.'/youtubechannel.php')
			OR !$copycontroller
			)
            return false;
		return true;
	}

	function installRewriteUrl()
	{
		$link_channel = 'youtubechannel';
		$link_channel_rewrite = 'youtubechannel';

		$sql = "INSERT INTO "._DB_PREFIX_."meta (id_meta ,page) VALUES (NULL , '".$link_channel."');";
		Db::getInstance()->ExecuteS($sql);

		$langs = Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'lang');

		foreach ($langs as $lang)
		{
			$id_lang = $lang['id_lang'];
			$id_meta = $this->getIdMeta($link_channel);
			$sql = "INSERT INTO "._DB_PREFIX_."meta_lang (id_meta ,	id_lang ,title , url_rewrite)
					VALUES (".$id_meta.", ".$id_lang.", 'Youtube Channel' , '".$link_channel_rewrite."');";
			Db::getInstance()->ExecuteS($sql);
		}
	}

	function uninstall()
	{
		$this->uninstallRewriteUrl();
		
		if (version_compare(_PS_VERSION_,'1.5','<')){
			$unlinkcontroller = @unlink(_PS_CONTROLLER_DIR_.'YoutubeChannelController.php');
		}
		else{
            $unlinkcontroller = @unlink(_PS_CONTROLLER_DIR_.'front/YoutubeChannelController.php');
		}    

		if (parent::uninstall() == false ||
	 		!Configuration::deleteByName('YT_USER') ||
			!Configuration::deleteByName('YT_DISPLAY_VIDEOS') ||
			!Configuration::deleteByName('YT_DESC_TRUNC') ||
			!Configuration::deleteByName('YT_HTML5') ||
			!Configuration::deleteByName('YT_AUTO_PLAY') ||
			!Configuration::deleteByName('YT_PLAYER_WIDTH') ||
			!Configuration::deleteByName('YT_PLAYER_HEIGHT') ||
			!Configuration::deleteByName('YT_MODULE_THUMB_WIDTH') ||
			!Configuration::deleteByName('YT_MODULE_THUMB_HEIGHT') ||
			!Configuration::deleteByName('YT_FEATURED_VIDEOS') ||
			!Configuration::deleteByName('YT_MODULE_ORDER') ||
			!Configuration::deleteByName('YT_VIDEO1') ||
			!Configuration::deleteByName('YT_VIDEO2') ||
			!Configuration::deleteByName('YT_MODULE_COLOR') ||
			!Configuration::deleteByName('YT_ICON_COLOR') ||
			!@unlink(_PS_ROOT_DIR_.'/youtubechannel.php') ||
			!$unlinkcontroller
	 	)
			return false;
		return true;
	}

	function uninstallRewriteUrl()
	{
		$link_channel = 'youtubechannel';

		$sql = "DELETE FROM "._DB_PREFIX_."meta WHERE page='".$link_channel."'";
		Db::getInstance()->ExecuteS($sql);

		$sql = "DELETE FROM "._DB_PREFIX_."meta_lang WHERE url_rewrite='".$link_channel."'";
		Db::getInstance()->ExecuteS($sql);
	}

	function getIdMeta($page)
	{
		$sql = "SELECT id_meta FROM "._DB_PREFIX_."meta WHERE page='".$page."'";
		$row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);

		return $row['id_meta'];
	}

	public function getContent()
	{
		$this->_html .= '<h2><img src="'.$this->_path.'img/youtube.png" alt=""/> '.$this->displayName.'</h2>';

		if (Tools::isSubmit('ytChannelGlobalFormSubmit'))
		{
			$yt_user = Tools::getValue('yt_user');
			$yt_display_videos = Tools::getValue('yt_display_videos');
			$yt_desc_trunc = Tools::getValue('yt_desc_trunc');
			$yt_html5 = Tools::getValue('yt_html5');
			$yt_player_width = Tools::getValue('yt_player_width');
			$yt_player_height = Tools::getValue('yt_player_height');
			$yt_auto_play = Tools::getValue('yt_auto_play');
			$modulecolor = Tools::getValue('modulecolor');
			$iconcolor = Tools::getValue('iconcolor');

			Configuration::updateValue('YT_USER', $yt_user);
			Configuration::updateValue('YT_DISPLAY_VIDEOS', $yt_display_videos);
			Configuration::updateValue('YT_DESC_TRUNC', $yt_desc_trunc);
			Configuration::updateValue('YT_HTML5', $yt_html5);
			Configuration::updateValue('YT_PLAYER_WIDTH', $yt_player_width);
			Configuration::updateValue('YT_PLAYER_HEIGHT', $yt_player_height);
			Configuration::updateValue('YT_AUTO_PLAY', $yt_auto_play);
			Configuration::updateValue('YT_MODULE_COLOR', $modulecolor);
			Configuration::updateValue('YT_ICON_COLOR', $iconcolor);

			$this->_html .= '<div class="conf">'.$this->l('Global settings updated').'</div>';
	    }

		elseif (Tools::isSubmit('ytChannelFormSubmit'))
		{
			$yt_module_thumb_width = Tools::getValue('yt_module_thumb_width');
			$yt_module_thumb_height = Tools::getValue('yt_module_thumb_height');
			$featured_videos = Tools::getValue('featured_videos');
			$yt_module_order = Tools::getValue('yt_module_order');
			$video1 = Tools::getValue('video1');
			$video2 = Tools::getValue('video2');

			Configuration::updateValue('YT_MODULE_THUMB_WIDTH', $yt_module_thumb_width);
			Configuration::updateValue('YT_MODULE_THUMB_HEIGHT', $yt_module_thumb_height);
			Configuration::updateValue('YT_FEATURED_VIDEOS', $featured_videos);
			Configuration::updateValue('YT_MODULE_ORDER', $yt_module_order);
			Configuration::updateValue('YT_VIDEO1', $video1);
			Configuration::updateValue('YT_VIDEO2', $video2);

			$this->_html .= '<div class="conf">'.$this->l('Block settings updated').'</div>';
	    }
		
		    if (version_compare(_PS_VERSION_,'1.5','<')){
			    $check_controller = _PS_CONTROLLER_DIR_.'YoutubeChannelController.php';
		    }
		    else{
                $check_controller = _PS_CONTROLLER_DIR_.'front/YoutubeChannelController.php';
		    }

            if (!file_exists($check_controller)) {
                $this->_html .= '<div class="warn"><b>'.$this->l('Warning').':</b> <i>"YoutubeChannelController.php"</i> '.$this->l('not on').' '.str_replace('YoutubeChannelController.php', '', $check_controller).'</div>';
            }
			if (!file_exists(_PS_ROOT_DIR_.'/youtubechannel.php')) {
                $this->_html .= '<div class="warn"><b>'.$this->l('Warning').':</b> <i>"youtubechannel.php"</i> '.$this->l('not on root directory').'.</div>';
            }

		$this->_html .= '
		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset>
			<legend><img src="'.$this->_path.'img/ytplay.png" alt="" title="" />'.$this->l('Global settings').'</legend>
			<br/>';
			
			$this->_html .= '<div id="global-settings">
				<label>'.$this->l('YouTube user').'</label>
				<div class="margin-form">
					<input type="text" name="yt_user" style="width: 200px;" value="'.Tools::getValue('yt_user', Configuration::get('YT_USER')).'" />
					<p class="preference_description clear">'.$this->l('The youtube username').'.</p>
				</div>
				<label>'.$this->l('Display videos').'</label>
				<div class="margin-form">
					<input type="text" name="yt_display_videos" style="width: 50px;" value="'.Tools::getValue('yt_display_videos', Configuration::get('YT_DISPLAY_VIDEOS')).'" />
					<p class="preference_description clear">'.$this->l('Videos to display in videos page').'.</p>
				</div>
				<label>'.$this->l('Video description').'</label>
				<div class="margin-form">
					<input type="text" name="yt_desc_trunc" style="width: 50px;" value="'.Tools::getValue('yt_desc_trunc', Configuration::get('YT_DESC_TRUNC')).'" />
					<p class="preference_description clear">'.$this->l('Truncate video description').'.</p>
				</div>
				<label>'.$this->l('Player width').'</label>
				<div class="margin-form">
					<input type="text" name="yt_player_width" style="width: 50px;" value="'.Tools::getValue('yt_player_width', Configuration::get('YT_PLAYER_WIDTH')).'" />
				</div>
				<label>'.$this->l('Player height').'</label>
				<div class="margin-form">
					<input type="text" name="yt_player_height" style="width: 50px;" value="'.Tools::getValue('yt_player_height', Configuration::get('YT_PLAYER_HEIGHT')).'" />
				</div>
				<label>'.$this->l('HTML5 player?').'</label>
				<div class="margin-form">
					<input type="radio" name="yt_html5" id="yt_html5_on" value="1" '.(Tools::getValue('yt_html5', Configuration::get('YT_HTML5')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="yt_html5_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="yt_html5" id="yt_html5_off" value="0" '.(!Tools::getValue('yt_html5', Configuration::get('YT_HTML5')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="yt_html5_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				<label>'.$this->l('Auto play?').'</label>
				<div class="margin-form">
					<input type="radio" name="yt_auto_play" id="yt_auto_play_on" value="1" '.(Tools::getValue('yt_auto_play', Configuration::get('YT_AUTO_PLAY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="yt_auto_play_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="yt_auto_play" id="yt_auto_play_off" value="0" '.(!Tools::getValue('yt_auto_play', Configuration::get('YT_AUTO_PLAY')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="yt_auto_play_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				<label>'.$this->l('Player theme').'</label>
				<div class="margin-form">
					<select name="modulecolor" style="width:100px;" />
					    <option value="0"'.(Configuration::get('YT_MODULE_COLOR') == '0' ? ' selected="selected"' : '').'>'.$this->l('Light').'</option>
					    <option value="1"'.(Configuration::get('YT_MODULE_COLOR') == '1' ? ' selected="selected"' : '').'>'.$this->l('Dark').'</option>
					</select>
				</div>
				<label>'.$this->l('Playbar').'</label>
				<div class="margin-form">
					<input type="radio" name="iconcolor" id="iconcolor_on" value="1" '.(Tools::getValue('iconcolor', Configuration::get('YT_ICON_COLOR')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="iconcolor_on"> '.$this->l('Red').'</label>
					<input type="radio" name="iconcolor" id="iconcolor_off" value="0" '.(!Tools::getValue('iconcolor', Configuration::get('YT_ICON_COLOR')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="iconcolor_off"> '.$this->l('White').'</label>
				</div>
				<div class="margin-form"><input type="submit" name="ytChannelGlobalFormSubmit" value="'.$this->l('Save').'" class="button" /></div>
				</div>
			</fieldset>
		</form><br/>';

		$this->_html .= '

		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset>
			<legend><img src="'.$this->_path.'img/ytstop.png" alt="" title="" />'.$this->l('Left/Right module settings').'</legend>
			<br/>
				<div id="block-settings">
				<label>'.$this->l('Thumbnail width').'</label>
				<div class="margin-form">
					<input type="text" name="yt_module_thumb_width" style="width: 50px;" value="'.Tools::getValue('yt_module_thumb_width', Configuration::get('YT_MODULE_THUMB_WIDTH')).'" />
				</div>
				<label>'.$this->l('Thumbnail height').'</label>
				<div class="margin-form">
					<input type="text" name="yt_module_thumb_height" style="width: 50px;" value="'.Tools::getValue('yt_module_thumb_height', Configuration::get('YT_MODULE_THUMB_HEIGHT')).'" />
				</div>
				<label>'.$this->l('Order mode').'</label>
				<div class="margin-form">
					<select name="yt_module_order" style="width:100px;" />
					    <option value="relevance"'.(Configuration::get('YT_MODULE_ORDER') == 'relevance' ? ' selected="selected"' : '').'>'.$this->l('Relevance').'</option>
					    <option value="published"'.(Configuration::get('YT_MODULE_ORDER') == 'published' ? ' selected="selected"' : '').'>'.$this->l('Published').'</option>
						<option value="viewCount"'.(Configuration::get('YT_MODULE_ORDER') == 'viewCount' ? ' selected="selected"' : '').'>'.$this->l('Viewed').'</option>
						<option value="rating"'.(Configuration::get('YT_MODULE_ORDER') == 'rating' ? ' selected="selected"' : '').'>'.$this->l('Rating').'</option>
					</select>
					<p class="preference_description clear">'.$this->l('Order shown when Videos ID is disabled').'.</p>
				</div>
				<label>'.$this->l('Videos ID').'</label>
				<div class="margin-form">
					<input type="radio" name="featured_videos" id="featured_videos_on" value="1" '.(Tools::getValue('featured_videos', Configuration::get('YT_FEATURED_VIDEOS')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="featured_videos_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="featured_videos" id="featured_videos_off" value="0" '.(!Tools::getValue('featured_videos', Configuration::get('YT_FEATURED_VIDEOS')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="featured_videos_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
					<p class="preference_description clear">'.$this->l('If disabled. Show 2 videos from your YouTube channel').'.</p>
				</div>
				<label>'.$this->l('Video ID 1').'</label>
				<div class="margin-form">
					<input type="text" name="video1" style="width: 100px;" value="'.Tools::getValue('video1', Configuration::get('YT_VIDEO1')).'" />
				</div>
				<label>'.$this->l('Video ID 2').'</label>
				<div class="margin-form">
					<input type="text" name="video2" style="width: 100px;" value="'.Tools::getValue('video2', Configuration::get('YT_VIDEO2')).'" />
					<p class="preference_description clear">'.$this->l('The video ID is the value of the "v" parameter in a videos URL').'.</p>
					<img style="border:1px solid #ccc;background-color: #fff;" src="'.$this->_path.'img/youtubeid.jpg" alt="" title="'.$this->l('Video ID in red').'." />
				</div>
				<div class="margin-form"><input type="submit" name="ytChannelFormSubmit" value="'.$this->l('Save').'" class="button" /></div>
				</div>
			</fieldset>
		</form>';
		
		return $this->_html;
	}

	public function hookHeader($params)
	{
	    global $smarty, $cookie;
		
		if (version_compare(_PS_VERSION_,'1.5','<'))
		{
    		Tools::addCSS($this->_path.'css/youtubechannel.css', 'all');
			Tools::addCSS(_PS_CSS_DIR_.'jquery.fancybox-1.3.4.css', 'all');
		    Tools::addJS(_PS_JS_DIR_.'jquery/jquery.fancybox-1.3.4.js');
    	}
		else
		{
			$this->context->controller->addCSS(($this->_path).'css/youtubechannel.css', 'all');
			$this->context->controller->addCSS(_PS_JS_DIR_.'jquery/plugins/fancybox/jquery.fancybox.css', 'all');
		    $this->context->controller->addJS(_PS_JS_DIR_.'jquery/plugins/fancybox/jquery.fancybox.js');	
		}
	}

	public function hookLeftColumn($params)
	{
		global $smarty, $cookie;

		$yt_user = Configuration::get('YT_USER');
		$yt_html5 = Configuration::get('YT_HTML5');
		$yt_player_width = Configuration::get('YT_PLAYER_WIDTH');
		$yt_player_height = Configuration::get('YT_PLAYER_HEIGHT');
		$yt_auto_play = Configuration::get('YT_AUTO_PLAY');
		$featured_videos = Configuration::get('YT_FEATURED_VIDEOS');
		$yt_module_thumb_width = Configuration::get('YT_MODULE_THUMB_WIDTH');
		$yt_module_thumb_height = Configuration::get('YT_MODULE_THUMB_HEIGHT');
		$yt_module_order = Configuration::get('YT_MODULE_ORDER');
		$modulecolor = Configuration::get('YT_MODULE_COLOR');
		$iconcolor = Configuration::get('YT_ICON_COLOR');
        
		if ($featured_videos == 1)
		{
			$video1 = array('videoID' => Configuration::get('YT_VIDEO1'));
		    $video2 = array('videoID' => Configuration::get('YT_VIDEO2'));

			    $videos_array = array($video1, $video2);
		
		    $smarty->assign(array('videos' => $videos_array));
		}

		$smarty->assign(array(
			'yt_user' => $yt_user,
			'yt_html5' => $yt_html5,
			'yt_player_width' => $yt_player_width,
			'yt_player_height' => $yt_player_height,
			'yt_auto_play' => $yt_auto_play,
			'yt_module_thumb_width' => $yt_module_thumb_width,
			'yt_module_thumb_height' => $yt_module_thumb_height,
			'featured_videos' => $featured_videos,
			'yt_module_order' => $yt_module_order,
			'modulecolor' => $modulecolor,
			'iconcolor' => $iconcolor
			));

		return $this->display(__FILE__, 'youtubechannel.tpl');
	}

	public function hookRightColumn($params)
	{
		return $this->hookLeftColumn($params);
	}
}
?>